package com.yjx.gulimall.product.service.impl;

import com.yjx.gulimall.product.entity.AttrEntity;
import com.yjx.gulimall.product.service.AttrService;
import com.yjx.gulimall.common.vo.product.BaseAttrs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjx.gulimall.common.utils.PageUtils;
import com.yjx.gulimall.common.utils.Query;

import com.yjx.gulimall.product.dao.ProductAttrValueDao;
import com.yjx.gulimall.product.entity.ProductAttrValueEntity;
import com.yjx.gulimall.product.service.ProductAttrValueService;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveProductAttrValue(Long spuId, List<BaseAttrs> baseAttrs) {

        if (!baseAttrs.isEmpty()) {
            //获取attrName
            List<Long> ids = baseAttrs.stream().map(BaseAttrs::getAttrId).collect(Collectors.toList());
            List<AttrEntity> attrEntities = attrService.getBatchByIds(ids);

            Map<Long, String> attrEntityMap = attrEntities
                                                .stream()
                                                .collect(Collectors.toMap(AttrEntity::getAttrId, AttrEntity::getAttrName));

            List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(baseAttr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setAttrId(baseAttr.getAttrId());
                productAttrValueEntity.setAttrName(attrEntityMap.get(baseAttr.getAttrId()));
                productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
                productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
                productAttrValueEntity.setSpuId(spuId);
                return productAttrValueEntity;
            }).collect(Collectors.toList());

            this.saveBatch(productAttrValueEntities);

        }
    }

}